//
//  PhotoAlbumViewController.m
//  PhotoGirl
//
//  Created by comic on 4/16/13.
//  Copyright (c) 2013 comic. All rights reserved.
//

#import "PhotoAlbumViewController.h"
#import <ASIHTTPRequest/ASIHTTPRequest.h>
#import "AlbumEntity.h"
#import "IoObjectRequest.h"
#import "AlbumDetailViewController.h"
#import "AppDelegate.h"

@interface PhotoAlbumViewController ()

@end

@implementation PhotoAlbumViewController
@synthesize photoAlbum=_photoAlbum;
@synthesize dataURL=_dataURL;

#pragma mark UIViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.parentViewController.navigationItem.title=@"Hotgirl Album";
    if (!self.dataURL) {
        self.dataURL=[NSString stringWithFormat:@"%@album",kPhotoAPIUrl];
    }
    UIActivityIndicatorView *indicarView=[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    self.loadingButton=[[UIBarButtonItem alloc] initWithCustomView:indicarView];
    self.refreshButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(reloadPhotoAlbum)];
    
}

- (void)viewDidAppear:(BOOL)animated {
    if (!self.photoAlbum) {
        [self reloadPhotoAlbum];
    }else {
        [self addRefreshButton:NO loading:NO];
    }
    
}
- (void)viewWillDisappear:(BOOL)animated {
    [[[AppDelegate sharedAppDelegate] downloadQueue] cancelAllOperations];

}
- (void)viewWillUnload {
    [[[AppDelegate sharedAppDelegate] downloadQueue] cancelAllOperations];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    
    // Dispose of any resources that can be recreated.
}

#pragma mark LoadPhotoData
- (void) setPhotoAlbum:(NSMutableArray *)photoAlbum {
    _photoAlbum=photoAlbum;
    [self.collectionView reloadData];
}

-(void) addRefreshButton:(BOOL)animated loading:(BOOL) loading {
    
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    if (!loading) {
        self.parentViewController.navigationItem.rightBarButtonItem=self.refreshButton;
    }else {
        self.parentViewController.navigationItem.rightBarButtonItem=self.loadingButton;
    }
  
}
- (void) reloadPhotoAlbum {
    [[[AppDelegate sharedAppDelegate] downloadQueue] cancelAllOperations];
    [self addRefreshButton:NO loading:YES];
    [(UIActivityIndicatorView *)self.loadingButton.customView startAnimating];
    // add loading view...
    if (!self.photoAlbum) {
        self.photoAlbum=[[NSMutableArray alloc] initWithCapacity:10];
    }
    NSURL *url = [NSURL URLWithString:self.dataURL];
    IoObjectRequest *request = [IoObjectRequest requestWithURL:url];
    [request setTimeOutSeconds:10];
    [request setInterfaceObject:self];
    [request setDelegate:self];
    [request setDidFinishSelector:@selector(requestDone:)];
    [request setDidFailSelector:@selector(requestWentWrong:)];
    [[[AppDelegate sharedAppDelegate] downloadQueue] addOperation:request];
}
-(void) loadAlbumImage {
    NSInvocationOperation *doneOp = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(didFinishQueue) object:nil];
    for (AlbumEntity* entity in self.photoAlbum) {
        NSURL *url = [NSURL URLWithString:entity.albumURL];
        IoObjectRequest *request = [IoObjectRequest requestWithURL:url];
        [request setDelegate:self];
        [request setInterfaceObject:entity];
        [request setDidFinishSelector:@selector(requestDone:)];
        [request setDidFailSelector:@selector(requestWentWrong:)];
        [[[AppDelegate sharedAppDelegate] downloadQueue] addOperation:request]; //queue is an NSOperationQueue
        [doneOp addDependency:request];
    }
    [[[AppDelegate sharedAppDelegate] downloadQueue] addOperation:doneOp];
}
#pragma mark ASI Request
- (void)requestDone:(IoObjectRequest *)request
{
    
    // truong hop load json
    if([request.interfaceObject isKindOfClass:[PhotoAlbumViewController class]]) {
        NSData *response = [request responseData];
        NSError *error=nil;
        NSArray *albumArray=[NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableContainers error:&error];
        if (!error) {
            NSMutableArray *album=[[NSMutableArray alloc] init];
                for(int i=0; i<albumArray.count; i++) {
                    if (i>0) {
                        AlbumEntity *entity=[[AlbumEntity alloc] init];
                        NSDictionary *jsonAlbum=[albumArray objectAtIndex:i];
                        entity.albumID=[jsonAlbum[ALBUM_ID] integerValue];
                        entity.albumName=jsonAlbum[ALBUM_NAME];
                        entity.albumURL=[NSString stringWithFormat:@"%@%@&WID=100&HEI=100&CVT=JPEG",kPhotoBaseURL,jsonAlbum[ALBUM_IMAGE]];
                        entity.imageAlbum=[[UIImageView alloc]init];
                        [album addObject:entity];
                    }
                }
            [self setPhotoAlbum:album];
            [self loadAlbumImage];
        } else {
            [[[UIAlertView alloc] initWithTitle:@"Lỗi trong quá trình tải album"
                                        message:error.localizedDescription
                                       delegate:nil
                              cancelButtonTitle:@"Đồng ý"
                              otherButtonTitles:nil] show];
            
        }
    } else if ([request.interfaceObject isKindOfClass:[AlbumEntity class]]) {
        UIImage *image=[UIImage imageWithData:request.rawResponseData];        
        AlbumEntity *entity=request.interfaceObject;
        [entity.imageAlbum setImage:image];
        if(entity.indexPath) {
            NSMutableArray *array=[[NSMutableArray alloc] initWithCapacity:1];
            [array addObject:entity.indexPath];
            [self.collectionView reloadItemsAtIndexPaths:array];
        }
    }
}
-(void) didFinishQueue {
    [(UIActivityIndicatorView *)self.loadingButton.customView stopAnimating];
    self.parentViewController.navigationItem.rightBarButtonItem=self.refreshButton;
}

- (void)requestWentWrong:(IoObjectRequest *)request
{
    NSError *error = [request error];
    if([request.interfaceObject isKindOfClass:[AlbumEntity class]]) {
        if (error.code!=4) {
        [[[UIAlertView alloc] initWithTitle:@"Lỗi trong quá trình tải album"
                                    message:error.localizedDescription
                                   delegate:nil
                          cancelButtonTitle:@"Đồng ý"
                          otherButtonTitles:nil] show];
        }
        
    }
    NSLog(@"%@-code:%d",error.localizedDescription,error.code);
}


#pragma mark UICollectionViewDataSource
- (PSUICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"Cell";
    AlbumEntity *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    AlbumEntity *album=[self.photoAlbum objectAtIndex:indexPath.row];
    cell.albumTitle.text=album.albumName;
    cell.imageAlbum.frame=CGRectMake((100-album.imageAlbum.image.size.width)/2,(100-album.imageAlbum.image.size.height)/2,album.imageAlbum.image.size.width,album.imageAlbum.image.size.height);
    album.indexPath=indexPath;
    [cell.imageAlbum setImage:album.imageAlbum.image];
    return cell;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.photoAlbum.count;
}

-(NSInteger)numberOfSectionsInCollectionView:(PSTCollectionView *)collectionView {
    return 1;
}

#pragma mark UICollectionViewDelegate
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    AlbumEntity *album=[self.photoAlbum objectAtIndex:indexPath.row];
    AlbumDetailViewController *controller=(AlbumDetailViewController* )[self.navigationController.storyboard instantiateViewControllerWithIdentifier:@"albumDetailViewController"];
    controller.navigationItem.title=album.albumName;
    controller.dataURL=[NSString stringWithFormat:@"%@list_photo?album_id=%d",kPhotoAPIUrl,album.albumID];
    [self.navigationController pushViewController:controller animated:YES];
}
@end
